package com.weibo.util;

import weibo4android.User;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import com.weibo.Sina;
import com.weibo.aaweibobean.AccountInfo;
import com.weibo.aaweibobean.OAuthConstant;

public class WeiboLogin {
	public static void login(Bundle bundle) {

		String id = "";
		String token = "";
		String tokenSecret = "";
		if (bundle != null) {
			id = bundle.getString(AccountInfo.ID);
			token = bundle.getString(AccountInfo.TOKEN);
			tokenSecret = bundle.getString(AccountInfo.TOKEN_SECRET);
		}
		OAuthConstant.getInstance().setUserId(Long.parseLong(id));
		OAuthConstant.getInstance().setToken(token);
		OAuthConstant.getInstance().setTokenSecret(tokenSecret);
		return;

	}

	public static void saveAccounts(SharedPreferences preferences, User user,
			OAuthConstant oAuthConstant) {
		String name = user.getScreenName();
		String id = String.valueOf(user.getId());
		for (int i = 0;; i++) {
			if (preferences.contains(AccountInfo.NICK + i)) { // 遍历所有帐号名
				if (preferences.getString(AccountInfo.NICK + i, "").equals(name)) { // 若已存在帐号名，则不保存
					break;
				}
			} else {
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString(AccountInfo.NICK + i, name);
				editor.putString(AccountInfo.ID + i, id);
				editor.putString(AccountInfo.TOKEN + i, oAuthConstant.getToken());
				editor.putString(AccountInfo.TOKEN_SECRET + i, oAuthConstant.getTokenSecret());
				editor.commit();
				break;
			}
		}
	}

	public static User getUser(Uri uri, OAuthConstant oAuthConstant) {

		try {
			RequestToken requestToken = oAuthConstant.getRequestToken();
			AccessToken accessToken = requestToken.getAccessToken(uri
					.getQueryParameter("oauth_verifier"));
			oAuthConstant.setAccessToken(accessToken);
			oAuthConstant.setUserId(accessToken.getUserId());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return verifyCredentials(OAuthConstant.getInstance().getUserId());
	}

	private static User verifyCredentials(long userId) {
		try {
			return Sina.getInstance().getWeibo().verifyCredentials();
		} catch (WeiboException e) {
			e.printStackTrace();
			return null;
		}
	}
}
